//
//  Teacher
//
//  Created by 洋 耿 on 15/7/2.
//  Copyright (c) 2015年 ZengYuan. All rights reserved.
//
#import "AWHttpTool.h"

@implementation AWHttpTool

+ (AFHTTPRequestOperation*)get:(NSString *)url params:(NSDictionary *)params success:(void (^)(id json))success failure:(void (^)(NSError *error))failure
{
    // 1.创建请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    mgr.responseSerializer.acceptableContentTypes = [mgr.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];

    
    // 2.发送请求
    AFHTTPRequestOperation*oper = [mgr GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSInteger code = [[operation.responseObject objectForKey:@"code"] integerValue];
        NSString *errStr= [operation.responseObject objectForKey:@"message"];
        
        if(!errStr || [errStr length]==0){
            errStr = @"数据请求失败";
        }
        
        NSError *err = [NSError errorWithDomain:errStr code:code userInfo:nil];
        if (failure) {
            failure(err);
        }
    }];
    
    return oper;
    
}

+ (AFHTTPRequestOperation*)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id json))success failure:(void (^)(NSError *error))failure
{
    // 1.创建请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    mgr.responseSerializer.acceptableContentTypes = [mgr.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];

    
    // 2.发送请求
    AFHTTPRequestOperation*oper = [mgr POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSInteger code = [[operation.responseObject objectForKey:@"code"] integerValue];

        NSString *errStr= [operation.responseObject objectForKey:@"message"];
        
        if(!errStr || [errStr length]==0){
            errStr = @"数据请求失败";
        }
        
        NSError *err = [NSError errorWithDomain:errStr code:code userInfo:nil];
        if (failure) {
            failure(err);
        }
    }];

    return oper;

}

+ (void)cancelRequest{
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    [mgr.operationQueue cancelAllOperations];
}

@end
